﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data;
using System.IO;

using Excel;

namespace BMCShowView.Business
{
    public static class LatestChange
    {
        public class Change
        {
            public string Id { get; set; }
            public string Content { get; set; }
            public DateTime Date { get; set; }
            public string Duration { get; set; }
            public string Handler { get; set; }
            public string Level { get; set; }
        }

        public static List<Change> ReadFromStream(Stream stream)
        {
            var result = new List<Change>();

            using (var reader = ExcelReaderFactory.CreateOpenXmlReader(stream))
            {
                reader.IsFirstRowAsColumnNames = true;
                using (var dataset = reader.AsDataSet())
                {
                    using (var table = dataset.Tables[0])
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            try
                            {
                                result.Add(new Change
                                {
                                    Id = row[0].ToString(),
                                    Content = row[1].ToString(),
                                    Date = row[2] is DateTime ? (DateTime)row[2] : DateTime.Parse(row[2].ToString()),
                                    Duration = row[3].ToString(),
                                    Handler = row[4].ToString(),
                                    Level = row[5].ToString()
                                });
                            }
                            catch (Exception e)
                            {
                                Trace.TraceError("解析最新变更的Excel文件出错：{0}\n{1}", row, e);
                            }
                        }
                    }
                }
            }

            return result;
        }
    }
}